package io.kiki.task.client.common.handler;

import io.kiki.task.client.common.Lifecycle;
import io.kiki.task.client.common.NettyClient;
import io.kiki.task.client.common.rpc.client.RequestBuilder;
import io.kiki.task.common.core.constant.SystemConstants.BEAT;
import io.kiki.task.common.core.enums.StatusEnum;
import io.kiki.task.common.core.model.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ClientRegister implements Lifecycle {
    public static final NettyClient CLIENT;
    public static final int REGISTER_TIME = 10;
    private static final ScheduledExecutorService SCHEDULE_EXECUTOR = Executors.newSingleThreadScheduledExecutor(
            r -> new Thread(r, "sj-client-register"));

    static {
        CLIENT = RequestBuilder.<NettyClient, HttpResponse>newBuilder()
                .client(NettyClient.class)
                .callback(
                        nettyResult -> {
                            if (StatusEnum.NO.getStatus().equals(nettyResult.getStatus())) {
                                log.error("heartbeat check requestId:[{}] message:[{}]", nettyResult.getRequestId(), nettyResult.getMessage());
                            }
                        })
                .build();
    }

    @Override
    public void start() {
        SCHEDULE_EXECUTOR.scheduleAtFixedRate(() -> {
            try {
                CLIENT.beat(BEAT.PING);
            } catch (Exception e) {
                log.error("发送心跳失败", e);
            }
        }, 0, REGISTER_TIME, TimeUnit.SECONDS);
    }

    @Override
    public void close() {

    }
}
